<template>
  <view class="profile-edit-page">
    <scroll-view class="scroll-content" :scroll-y="true">
      <view class="avatar-section" @click="chooseAvatar">
        <image class="avatar-preview" :src="formData.avatar" mode="aspectFill"></image>
        <view class="camera-icon-bg">
          <image class="camera-icon" src="/static/icons/camera.svg"></image>
        </view>
      </view>

      <view class="form-container">
        <view class="form-group">
          <text class="label">账户名</text>
          <input type="text" class="input-field" v-model="formData.username" />
        </view>
        <view class="form-group">
          <text class="label">姓名</text>
          <input type="text" class="input-field" v-model="formData.realName" />
        </view>
        <view class="form-group">
          <text class="label">手机号</text>
          <input type="number" class="input-field" v-model="formData.phone" />
        </view>
      </view>

      <view class="section-title">修改密码</view>
      <view class="form-container">
        <view class="form-group">
          <text class="label">新密码</text>
          <view class="input-wrapper">
            <input :type="passwordFieldType.new" class="input-field" v-model="formData.newPassword" placeholder="请输入新密码" placeholder-class="placeholder" />
            <image 
              class="password-toggle"
              :src="passwordFieldType.new === 'password' ? '/static/icons/eye-slash.svg' : '/static/icons/eye-open.svg'"
              @click="togglePasswordVisibility('new')"
            ></image>
          </view>
        </view>
        <view class="form-group">
          <text class="label">确认密码</text>
          <view class="input-wrapper">
            <input :type="passwordFieldType.confirm" class="input-field" v-model="formData.confirmPassword" placeholder="请再次输入新密码" placeholder-class="placeholder" />
            <image 
              class="password-toggle"
              :src="passwordFieldType.confirm === 'password' ? '/static/icons/eye-slash.svg' : '/static/icons/eye-open.svg'"
              @click="togglePasswordVisibility('confirm')"
            ></image>
          </view>
        </view>
      </view>

      <button class="save-btn" @click="saveProfile">保存修改</button>
    </scroll-view>
  </view>
</template>

<script setup>
import { reactive } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { request } from '@/utils/request.js';
import { BASE_URL } from '@/utils/config.js';

// ---- 响应式状态定义 ----
const formData = reactive({
  avatar: '',
  username: '', // 对应 accountUsername
  realName: '', // 对应 userName
  phone: '',    // 对应 userPhone
  newPassword: '',
  confirmPassword: '',
  originalAvatar: '', // 存储原始相对路径
});

const passwordFieldType = reactive({ new: 'password', confirm: 'password' });

// ---- Methods ----
const chooseAvatar = () => {
  uni.chooseImage({
    count: 1, sizeType: ['compressed'],
    success: (res) => {
      formData.avatar = res.tempFilePaths[0];
    },
  });
};

const togglePasswordVisibility = (field) => {
  passwordFieldType[field] = passwordFieldType[field] === 'password' ? 'text' : 'password';
};

const saveProfile = async () => {
  if (formData.newPassword && formData.newPassword !== formData.confirmPassword) {
    return uni.showToast({ title: '两次输入的密码不一致', icon: 'none' });
  }
  uni.showLoading({ title: '保存中...' });
  
  try {
    let uploadedAvatarUrl = formData.originalAvatar;

    if (formData.avatar && !formData.avatar.startsWith('http')) {
      const uploadResult = await new Promise((resolve, reject) => {
        uni.uploadFile({
          url: BASE_URL + '/upload',
          filePath: formData.avatar,
          name: 'file',
          header: { 'X-User-ID': uni.getStorageSync('userId') },
          success: (res) => {
            const resData = JSON.parse(res.data);
            if (resData.code === 200) resolve(resData.data.url);
            else reject(new Error(resData.msg || '上传失败'));
          },
          fail: reject,
        });
      });
      uploadedAvatarUrl = uploadResult;
    }

    const updateParams = {
      accountUsername: formData.username,
      userName: formData.realName,
      userPhone: formData.phone,
      userImg: uploadedAvatarUrl,
    };
    if (formData.newPassword) {
      updateParams.accountPassword = formData.newPassword;
    }

    const updatedUserInfo = await request({
      url: '/my/updateProfile',
      method: 'PUT', // 使用 PUT
      data: updateParams,
    });
    
    // [关键] 更新本地存储
		console.log(updatedUserInfo);
    uni.setStorageSync('userInfo', updatedUserInfo);

    uni.hideLoading();
    uni.showToast({ title: '保存成功！', icon: 'success' });
    setTimeout(() => uni.navigateBack(), 1500);

  } catch (error) {
    uni.hideLoading();
    console.error('保存失败:', error);
  }
};

// ---- 生命周期钩子 ----
onLoad(() => {
  const storedUserInfo = uni.getStorageSync('userInfo');
  if (storedUserInfo) {
    formData.avatar = `${BASE_URL}${storedUserInfo.userImg}`;
    formData.originalAvatar = storedUserInfo.userImg;
    formData.username = storedUserInfo.accountUsername || '';
    formData.realName = storedUserInfo.userName;
    formData.phone = storedUserInfo.userPhone;
  }
});
</script>

<style lang="scss" scoped>
.profile-edit-page {
  background-color: $uni-bg-color-white;
  height: 100vh;
}

.scroll-content {
  height: 100%;
}

.avatar-section {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 50rpx 0;
  position: relative;
  
  .avatar-preview {
    width: 180rpx;
    height: 180rpx;
    border-radius: 50%;
  }

  .camera-icon-bg {
    position: absolute;
    // 微调位置使其精确覆盖在头像右下角
    top: 50%;
    left: 50%;
    transform: translate(40rpx, 40rpx);
    
    width: 56rpx;
    height: 56rpx;
    background-color: $uni-primary;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    border: 4rpx solid white;
    
    .camera-icon {
      width: 28rpx;
      height: 28rpx;
    }
  }
}

.form-container {
  padding: 0 40rpx;
}

.form-group {
  display: flex;
  align-items: center;
  min-height: 110rpx;
  border-bottom: 1px solid $uni-border-color;
  
  .label {
    font-size: 32rpx;
    color: $uni-text-color;
    width: 160rpx; /* 固定标签宽度 */
    flex-shrink: 0;
  }
  
  .input-wrapper {
    position: relative;
    flex-grow: 1;
    display: flex;
    align-items: center;
  }
  
  .input-field {
    flex-grow: 1;
    border: none;
    outline: none;
    font-size: 32rpx;
    color: $uni-text-color;
    text-align: right;
    
    &.placeholder {
        color: $uni-text-color-placeholder;
    }
  }
  
  .password-toggle {
    width: 44rpx;
    height: 44rpx;
    margin-left: 20rpx;
    flex-shrink: 0;
  }
}

.section-title {
  color: $uni-text-color-light;
  font-size: 28rpx;
  padding: 50rpx 40rpx 20rpx;
}

.save-btn {
  width: calc(100% - 80rpx);
  height: 90rpx;
  line-height: 90rpx;
  margin: 80rpx 40rpx;
  background: linear-gradient(135deg, $uni-primary, $uni-accent);
  color: white;
  border-radius: 45rpx;
  font-size: 32rpx;
  font-weight: 500;
}
</style>